require 'ajax_scaffold'

class Task < ActiveRecord::Base

  belongs_to :sprint
  belongs_to :user
  has_many :estimates, :order => "date", :dependent => :destroy 
  validates_presence_of :initial_estimate, :ticket_id #,:sprint
  validates_uniqueness_of :ticket_id
  validates_inclusion_of :initial_estimate, :in => 0..16,
                         :message => 'must be a number between 1 and 9'
 
   @scaffold_columns = [ 
       AjaxScaffold::ScaffoldColumn.new(self, { :name => "ticket_id", :label => "Ticket" }),
       AjaxScaffold::ScaffoldColumn.new(self, { :name => "name", :sortable => false }),
       AjaxScaffold::ScaffoldColumn.new(self, { :name => "initial_estimate", :label => "Initial Estimate" }),
       AjaxScaffold::ScaffoldColumn.new(self, { :name => "notes" }),
       AjaxScaffold::ScaffoldColumn.new(self, { :name => "user", :eval => "task.user.short_username", :sort_sql=> "user_id"}),
       AjaxScaffold::ScaffoldColumn.new(self, { :name => "sprint", :eval => "task.sprint.name", :sort_sql => "sprint_id" })
   
   ]
                              
  def new_initial_estimate
    initial_estimate
  end
  
  def new_initial_estimate=(new_initial_estimate) 
    self.initial_estimate = new_initial_estimate 
    self.estimates.each do |e|
      e.hours = self.initial_estimate
      e.save
    end
  end 

  
  def current_estimate
    e = estimate_for_date(Date.today)
    if e.nil?
      0
    else
      e.hours
    end
  end
  
  # scroll through all the estimates starting with a specific date
  # and set them to the new hours estimate.
  def update_estimate (date, hours)
    while date <= sprint.stop_date 
      estimate = estimate_for_date(date)
      if !estimate.nil?
        estimate.hours = hours
        estimate.save
      end
      date = date + 1
    end
  end
  
  # return the estimate for a date, or nil if not found
  def estimate_for_date (date)
    matching_estimates = self.estimates.select { |estimate|
      estimate.date == date
    }
    if matching_estimates.size ==1
      estimate = matching_estimates[0]
    else
      nil
    end

  end
  
  
end
